# -*- coding: utf-8 -*-
from flask import request, g
from common.token import verify_token
from common.response import error
from common.error_code import ErrorCode
from functools import wraps

def auth_required(f):
    """验证Token的装饰器"""
    @wraps(f)
    def wrapper(*args, **kwargs):
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return error(ErrorCode.UNAUTHORIZED, "未提供有效的Token")
            
        token = auth_header.split(' ')[1]
        payload = verify_token(token)
        
        if not payload:
            return error(ErrorCode.UNAUTHORIZED, "Token已过期或无效")
            
        # 将用户信息存入g对象
        g.user_id = payload.get('user_id')
        g.role = payload.get('role')
        g.name = payload.get('name')
        g.class_id = payload.get('class_id')
        g.teacher_position = payload.get('teacher_position')
        g.student_id = payload.get('student_id')
        
        return f(*args, **kwargs)
    return wrapper